import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'core/theme.dart';
import 'core/constants.dart';
import 'shared/services/storage_service.dart';
import 'shared/services/coin_purchase_service.dart';
import 'shared/services/att_service.dart';
import 'shared/providers/word_provider.dart';
import 'features/home/home_page.dart';
import 'features/learning/learning_page.dart';
import 'features/profile/profile_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize storage service
  final storageService = StorageService();
  await storageService.init();
  
  // Request App Tracking Transparency permission (iOS only)
  // This will block until user responds, ensuring privacy compliance
  try {
    final trackingStatus = await ATTService.requestTrackingPermission();
    print('ATT: Final tracking status: ${ATTService.getStatusDescription(trackingStatus)}');
  } catch (e) {
    print('ATT: Error requesting tracking permission: $e');
  }
  
  // Initialize purchase service (optional - will be initialized when first used)
  try {
    final purchaseService = CoinPurchaseService();
    await purchaseService.initialize();
  } catch (e) {
    // Purchase service initialization failed, but app can still run
    print('Purchase service initialization failed: $e');
  }
  
  runApp(
    ProviderScope(
      overrides: [
        storageServiceProvider.overrideWithValue(storageService),
      ],
      child: const HuggoApp(),
    ),
  );
}

class HuggoApp extends StatelessWidget {
  const HuggoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: AppConstants.APP_NAME,
      theme: AppTheme.lightTheme,
      home: const MainNavigationPage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MainNavigationPage extends StatefulWidget {
  const MainNavigationPage({super.key});

  @override
  State<MainNavigationPage> createState() => _MainNavigationPageState();
}

class _MainNavigationPageState extends State<MainNavigationPage>
    with TickerProviderStateMixin {
  int _selectedIndex = 0;
  late AnimationController _pageAnimationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _rotationAnimation;

  final List<Widget> _pages = [
    const HomePage(),
    const LearningPage(),
    const ProfilePage(),
  ];

  final List<NavigationItem> _navigationItems = [
    NavigationItem(
      icon: FontAwesomeIcons.house,
      selectedIcon: FontAwesomeIcons.house,
      label: 'Home',
    ),
    NavigationItem(
      icon: FontAwesomeIcons.graduationCap,
      selectedIcon: FontAwesomeIcons.graduationCap,
      label: 'Learning',
    ),
    NavigationItem(
      icon: FontAwesomeIcons.user,
      selectedIcon: FontAwesomeIcons.solidUser,
      label: 'Profile',
    ),
  ];

  @override
  void initState() {
    super.initState();
    _pageAnimationController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeInOutCubic,
    ));
    
    _scaleAnimation = Tween<double>(
      begin: 0.95,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeOutBack,
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeOutCubic,
    ));
    
    _rotationAnimation = Tween<double>(
      begin: 0.02,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeOutQuart,
    ));
    
    // Start initial animation
    _pageAnimationController.forward();
  }

  @override
  void dispose() {
    _pageAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedBuilder(
        animation: _pageAnimationController,
        builder: (context, child) {
          return Transform(
            alignment: Alignment.center,
            transform: Matrix4.identity()
              ..setEntry(3, 2, 0.001) // perspective
              ..rotateX(_rotationAnimation.value)
              ..rotateY(_rotationAnimation.value * 0.5),
            child: SlideTransition(
              position: _slideAnimation,
              child: FadeTransition(
                opacity: _fadeAnimation,
                child: ScaleTransition(
                  scale: _scaleAnimation,
                  child: Container(
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(
                            0.1 * (1 - _fadeAnimation.value),
                          ),
                          spreadRadius: 2,
                          blurRadius: 20,
                          offset: Offset(0, 5 * (1 - _fadeAnimation.value)),
                        ),
                      ],
                    ),
                    child: IndexedStack(
                      index: _selectedIndex,
                      children: _pages,
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
      bottomNavigationBar: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(24),
            topRight: Radius.circular(24),
          ),
          boxShadow: [
            BoxShadow(
              color: AppConstants.PRIMARY_BLUE.withOpacity(0.08),
              spreadRadius: 2,
              blurRadius: 20,
              offset: const Offset(0, -8),
            ),
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 10,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: SafeArea(
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.white.withOpacity(0.95),
                  Colors.white,
                ],
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: _navigationItems.asMap().entries.map((entry) {
                  final index = entry.key;
                  final item = entry.value;
                  final isSelected = _selectedIndex == index;

                return Material(
                  color: Colors.transparent,
                  child: InkWell(
                    borderRadius: BorderRadius.circular(25),
                    onTap: () => _onItemTapped(index),
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 400),
                      curve: Curves.easeInOutCubic,
                      padding: EdgeInsets.symmetric(
                        horizontal: isSelected ? 24 : 16, 
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        gradient: isSelected
                            ? LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                                colors: [
                                  AppConstants.PRIMARY_BLUE.withOpacity(0.15),
                                  AppConstants.PRIMARY_BLUE.withOpacity(0.08),
                                ],
                              )
                            : null,
                        borderRadius: BorderRadius.circular(25),
                        border: isSelected 
                            ? Border.all(
                                color: AppConstants.PRIMARY_BLUE.withOpacity(0.3), 
                                width: 1.5,
                              )
                            : null,
                        boxShadow: isSelected
                            ? [
                                BoxShadow(
                                  color: AppConstants.PRIMARY_BLUE.withOpacity(0.2),
                                  spreadRadius: 1,
                                  blurRadius: 8,
                                  offset: const Offset(0, 4),
                                ),
                              ]
                            : null,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          AnimatedContainer(
                            duration: const Duration(milliseconds: 300),
                            padding: EdgeInsets.all(isSelected ? 4 : 0),
                            decoration: BoxDecoration(
                              color: isSelected 
                                  ? AppConstants.PRIMARY_BLUE.withOpacity(0.1)
                                  : Colors.transparent,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: AnimatedScale(
                              scale: isSelected ? 1.1 : 1.0,
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.easeInOutBack,
                              child: TweenAnimationBuilder<Color?>(
                                duration: const Duration(milliseconds: 300),
                                tween: ColorTween(
                                  begin: Colors.grey[600],
                                  end: isSelected 
                                      ? AppConstants.PRIMARY_BLUE 
                                      : Colors.grey[600],
                                ),
                                builder: (context, color, child) {
                                  return FaIcon(
                                    isSelected ? item.selectedIcon : item.icon,
                                    color: color,
                                    size: 18,
                                  );
                                },
                              ),
                            ),
                          ),
                          AnimatedSize(
                            duration: const Duration(milliseconds: 400),
                            curve: Curves.easeInOutCubic,
                            child: AnimatedSwitcher(
                              duration: const Duration(milliseconds: 300),
                              transitionBuilder: (child, animation) {
                                return SlideTransition(
                                  position: Tween<Offset>(
                                    begin: const Offset(0.3, 0),
                                    end: Offset.zero,
                                  ).animate(animation),
                                  child: FadeTransition(
                                    opacity: animation,
                                    child: child,
                                  ),
                                );
                              },
                              child: isSelected
                                  ? Row(
                                      key: ValueKey(item.label),
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        const SizedBox(width: 8),
                                        TweenAnimationBuilder<double>(
                                          duration: const Duration(milliseconds: 400),
                                          tween: Tween(begin: 0.0, end: 1.0),
                                          curve: Curves.easeOutBack,
                                          builder: (context, value, child) {
                                            return Transform.scale(
                                              scale: value,
                                              child: Text(
                                                item.label,
                                                style: TextStyle(
                                                  color: AppConstants.PRIMARY_BLUE,
                                                  fontWeight: FontWeight.w700,
                                                  fontSize: 14,
                                                  letterSpacing: 0.5,
                                                ),
                                              ),
                                            );
                                          },
                                        ),
                                      ],
                                    )
                                  : const SizedBox.shrink(),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }).toList(),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void _onItemTapped(int index) {
    if (index == _selectedIndex) return;
    
    // Create a smooth transition by first fading out, then changing page, then fading in
    _pageAnimationController.reverse().then((_) {
      setState(() {
        _selectedIndex = index;
      });
      _pageAnimationController.forward();
    });
  }
}

class NavigationItem {
  final IconData icon;
  final IconData selectedIcon;
  final String label;

  NavigationItem({
    required this.icon,
    required this.selectedIcon,
    required this.label,
  });
}
